<template>
  <el-dialog
    v-model="dialogFormVisible"
    :title="title"
    width="500px"
    @close="close"
  >
    <el-form ref="formRef" label-width="80px" :model="form" :rules="rules">
      <el-form-item label="上级部门" prop="cateid">
        <el-tree-select
          v-model="form.cateid"
          :data="treePartData"
          filterable
          :render-after-expand="false"
          style="width: 100%"
          check-strictly
          check-on-click-node
        />
      </el-form-item>
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="类型" prop="iswangge">
        <el-radio v-model="form.iswangge" checked label="1">层级</el-radio>
        <el-radio v-model="form.iswangge" label="2">部门</el-radio>
        <el-radio v-model="form.iswangge" label="3">辖区</el-radio>
      </el-form-item>
      <el-form-item label="officeid" prop="">
        <el-input v-model="form.officeId" />
      </el-form-item>
      <el-form-item label="townid" prop="">
        <el-input v-model="form.townId" />
      </el-form-item>
      <el-form-item label="简介" prop="description">
        <el-input v-model="form.description" />
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input v-model="form.sort" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取消</el-button>
      <el-button type="primary" @click="confirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script>
  import { defineComponent, reactive, toRefs, inject } from 'vue'
  import {
    doEdit,
    doAdd,
    getList as getPartList,
  } from '@/api/departmentManagement'
  import { convertedTreeNode } from '@/utils/index'
  import { nextTick } from 'vue'

  export default defineComponent({
    name: 'DepartmentManagementEdit',
    emits: ['fetch-data'],
    setup(props, { emit }) {
      const $baseMessage = inject('$baseMessage')

      const state = reactive({
        formRef: null,
        treePartData: [],
        form: {
          cateid: [],
          name: '',
          townId: '',
          officeId: '',
          description: '',
          sort: '0',
        },
        rules: {
          cateid: [
            { required: true, trigger: 'blur', message: '请选择上级部门' },
          ],
          name: [{ required: true, trigger: 'blur', message: '请输入名称' }],
          iswangge: [
            { required: true, trigger: 'blur', message: '请选择类型' },
          ],
          sort: [{ required: true, trigger: 'blur', message: '请输入排序' }],
        },
        title: '',
        dialogFormVisible: false,
      })

      const fetchPartData = async () => {
        try {
          const {
            data: { list },
          } = await getPartList()
          state.treePartData = convertedTreeNode(list)
        } catch (error) {
          console.error('Error fetching part data:', error)
        }
      }

      const handleNodeClick = (node) => {
        state.form.parentName = node.name
        state.form.parentId = node.id
      }

      const showEdit = async (row) => {
        await fetchPartData()

        if (!row) {
          state.title = '添加'
        } else {
          state.title = '编辑'
          nextTick(() => {
            // 渲染父级
            state.form.cateid = row.cateid
          })
          state.form = { ...row }
        }
        state.dialogFormVisible = true
      }

      const close = () => {
        state.formRef.resetFields()
        state.form = {
          cateid: [],
          name: '',
          sort: '',
        }
        state.dialogFormVisible = false
      }

      const save = async () => {
        try {
          await state.formRef.validate()
          const { msg } = await doEdit(state.form)
          $baseMessage(msg, 'success', 'vab-hey-message-success')
          emit('fetch-data')
          close()
        } catch (error) {
          console.error('Error saving data:', error)
        }
      }

      const add = async () => {
        try {
          await state.formRef.validate()
          const { msg } = await doAdd(state.form)
          $baseMessage(msg, 'success', 'vab-hey-message-success')
          emit('fetch-data')
          close()
        } catch (error) {
          console.error('Error saving data:', error)
        }
      }

      const confirm = async () => {
        if (state.title == '编辑') {
          save()
        } else {
          add()
        }
      }

      return {
        ...toRefs(state),
        handleNodeClick,
        showEdit,
        close,
        save,
        confirm,
      }
    },
  })
</script>
